<?php


namespace app\game;


use app\game\node\AbsNode;
use app\game\node\INode;
use app\game\node\NodeForm;

class Form
{
    /**
     * 每行展示几个位置
     * @var int
     */
    protected $width = 10;

    /**
     * 共计行数
     * @var int
     */
    protected $height = 10;

    /**
     * 每个位置存放的数据
     * @var array
     */
    protected $pointers;

    /**
     * @param int $height
     */
    public function setHeight($height)
    {
        $this->height = $height;
    }

    /**
     * @param int $width
     */
    public function setWidth($width)
    {
        $this->width = $width;
    }


    public function getNode($row, $col)
    {
        return $this->pointers[$row][$col];
    }

    /**
     * 获取所有可用的节点
     * @return array
     */
    public function getAllFormNode()
    {
        $formArr = [];

        $this->each(function(&$node, $row, $col) use (&$formArr){
            if ($node instanceof NodeForm){
                $formArr[] = $node;
            }
        });

        return $formArr;
    }

    /**
     * @param $row
     * @param $col
     * @param AbsNode $node
     */
    public function setRowColNode($row, $col, AbsNode $node)
    {
        $this->pointers[$row][$col] = $node;
    }

    /**
     * @param callable $call
     */
    private function each($call)
    {
        for ($row = 0; $row < $this->height; $row++)
        {
            for ($col = 0; $col < $this->width; $col++)
            {
                $call($this->pointers[$row][$col],$row,$col);
            }
        }
    }

    public function init()
    {
        $this->each(function (&$node, $row, $col){
            $node = new NodeForm($row,$col);
        });
    }

    private function clearPrint()
    {
        $str = '';
        for ($row = 0; $row < $this->height + 10; $row++)
        {
            $str .= PHP_EOL;
        }
        echo $str;
    }

    public function show()
    {
        $this->clearPrint();
        $str = '';
        for ($row = 0; $row < $this->height; $row++)
        {
            for ($col = 0; $col < $this->width; $col++)
            {
                $str .=($this->pointers[$row][$col])->show();
            }
            $str .= PHP_EOL;
        }

        echo $str;
    }

}